﻿using System.Linq;
using System.Web.Mvc;
using ComeSeeThis_MVC2.Models;

namespace ComeSeeThis_MVC2.Controllers
{
    public class VehicleController : Controller
    {
        readonly VehicleRepository _vehicleRepository = new VehicleRepository();
        readonly VehicleSpurRepository _vehicleSpurRepository = new VehicleSpurRepository();

        #region Get Methods

        public ActionResult Index(int page = 0, int pageSize = 15)
        {
            //const int pageSize = 10;
            var vehicles = _vehicleRepository.GetAllVehicles(false);
            var comps = new CompanyRepository().GetAllCompanies(1, ProductType.Vehicle, true, true);
            var companies = new SelectList(comps, "CompanyId", "CompanyName");
            ViewData["Companies"] = companies;

            //var paginatedVehicles = new PaginatedList<Vehicle>(vehicles, page, pageSize);

            return View(vehicles);
        }

        public ActionResult IndexVehicleList(int companyId)
        {
            var vehicles = _vehicleRepository.GetAllVehiclesByCompany(companyId);
            return View("VehicleList", vehicles);
        }

        public ActionResult Type(int vehicleTypeId)
        {
            var vehicles = from v in _vehicleRepository.GetAllVehicles(false)
                           where v.VehicleTypeId == vehicleTypeId
                           orderby v.VehicleName
                           select v;

            return View(vehicles.ToList());
        }

        public ActionResult Details(int id)
        {
            var vehicle = _vehicleRepository.GetVehicle(id);

            if (vehicle == null) return View("VehicleNotFound");

            return View(vehicle);
        }

        #endregion

        public ActionResult NotAuthorizedToEdit(int id)
        {
            return View();
        }
        public ActionResult VehicleNotFound()
        {
            return View();
        }
        
        #region Edit Methods

        [Authorize]
        public ActionResult Edit(int id)
        {
            var vehicle = _vehicleRepository.GetVehicle(id);
            if (vehicle == null) return View("VehicleNotFound");

            // Check if this user can edit this
            if (!CheckPermission(vehicle.SubmittedBy)) RedirectToAction("NotAuthorizedToEdit", new { id = vehicle.VehicleId});
            return View(new VehicleFormView(vehicle));
        }

        [HttpPost, Authorize]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            var vehicle = _vehicleRepository.GetVehicle(id);
            if (vehicle == null) return View("VehicleNotFound");

            if (!CheckPermission(vehicle.SubmittedBy)) return RedirectToAction("NotAuthorizedToEdit", new { id = vehicle.VehicleId });

            if (TryUpdateModel(vehicle, "Vehicle"))
            {
                _vehicleRepository.Save();
                return RedirectToAction("Details", new { id = vehicle.VehicleId });
            }
            return View(new VehicleFormView(vehicle));
        }

        [HttpPost, Authorize]
        public ActionResult SubmitSpurGear(int vehicleId, int spur)
        {
            if (Request.IsAjaxRequest())
            {
                //var context = new ComeSeeThisDBEntities();
                //context.VehicleTypes.Where(x => x.VehicleTypeId == vehicleTypeId).First();
                var vehicleSpur = new VehicleSpur {VehicleId = vehicleId, SpurGear = spur};
                _vehicleSpurRepository.Add(vehicleSpur);
                _vehicleSpurRepository.Save();

                return View("VehicleSpurList", new {id = vehicleId});
            }
            return View("Edit", vehicleId);

        }

        //public ActionResult VehicleSpurList(int id)
        //{
        //    //var vehicle = _vehicleRepository.GetVehicle(id);
        //    var vehicleSpurs = _vehicleSpurRepository.GetAllVehicleSpursByVehicleId(id);
        //    return View(vehicleSpurs);
        //}

        #endregion

        #region Create Methods

        [Authorize]
        public ActionResult Create()
        {
            var vehicle = new Vehicle();
            ViewData["IsAdmin"] = false;
            return View(new VehicleFormView(vehicle));
        }

        [HttpPost, Authorize]
        public ActionResult Create(Vehicle vehicle)
        {
            if (ModelState.IsValid)
            {
                vehicle.SubmittedBy = User.Identity.Name;
                _vehicleRepository.Add(vehicle);
                _vehicleRepository.Save();

                if (vehicle.Approved) RedirectToAction("Index");
                return RedirectToAction("Submitted", new { id = vehicle.VehicleId});
                //return RedirectToAction("Index");
            }
            return View(new VehicleFormView(vehicle));
        }
        public ActionResult Submitted(int id)
        {
            var vehicle = _vehicleRepository.GetVehicle(id);

            return View(vehicle);
        }

        [HttpPost, Authorize]
        public ActionResult SubmitSpur(int spur, int vehicleId)
        {
            if (Request.IsAjaxRequest())
            {
                var vehicleSpur = new VehicleSpur { SpurGear = spur, VehicleId = vehicleId };
                // Check if this spur and vehicle combo already exists
                if (!_vehicleSpurRepository.SpurExists(vehicleId, spur))
                {
                    // Add it to the db
                    _vehicleSpurRepository.Add(vehicleSpur);
                    _vehicleSpurRepository.Save();

                    var spurs = _vehicleSpurRepository.GetAllVehicleSpursByVehicleId(vehicleId);
                    return View("SpurList", spurs);
                }
                const string fragment = "Spur gear already exists";
                return Content(fragment);
            }
            return View("Index");
        }
        
        #endregion

        #region Delete Methods

        [Authorize]
        public ActionResult Delete(int id)
        {
            var vehicle = _vehicleRepository.GetVehicle(id);
            if (vehicle == null) return RedirectToAction("VehicleNotFound");

            if (!CheckPermission(vehicle.SubmittedBy)) return RedirectToAction("NotAuthorizedToEdit");

            // Check if there are Gearing Recs for this vehicle, if so, it can't be deleted.
            var boo = new GearingRecRepository().GetAllGearingRecsByVehicleId(id);
            
            if (boo.ToList().Count > 0) return RedirectToAction("NotAuthorizedToEdit");
            
            return View(vehicle);
        }

        [HttpPost, Authorize]
        public ActionResult Delete(int id, string confirmButton)
        {
            var vehicle = _vehicleRepository.GetVehicle(id);

            if (vehicle == null) return View("VehicleNotFound");

            _vehicleRepository.Delete(vehicle);
            _vehicleRepository.Save();

            return RedirectToAction("Index");
        }

        [Authorize]
        public ActionResult DeleteSpur(int id, int vehicleId)
        {
            var spur = _vehicleSpurRepository.GetVehicleSpur(id);

            if (spur == null) return View("VehicleNotFound");

            _vehicleSpurRepository.Delete(spur);
            _vehicleSpurRepository.Save();

            var spurs = _vehicleSpurRepository.GetAllVehicleSpursByVehicleId(vehicleId);
            return View("SpurList", spurs);
        }
        #endregion

        // Check permissions
        private bool CheckPermission(string submittedBy)
        {
            // Check if this user can edit this
            if (User.IsInRole("SiteAdmin") || User.IsInRole("GearingAdmin")) return true;
            return submittedBy.ToLower() == User.Identity.Name.ToLower();
        }
    }
}
